package com.mkb.conf;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author meikb
 * @desc
 * @date 2024-03-15 11:35
 */
public class CacheUtils {
    static Cache<String, Object> cache1 = CacheBuilder.newBuilder().build();
    static Cache<String, Object> cacheExprie = null;

    public static void set(String key, String value){
        cache1.put(key, value);
    }

    public static void set(String key, String value, Long time, TimeUnit timeUnit){
        cacheExprie = CacheBuilder.newBuilder().expireAfterWrite(time, timeUnit).build();
        cacheExprie.put(key, value);
    }

    public static Boolean setIfAbsent(String key, String value, Long time, TimeUnit timeUnit){
        try {
            if (cacheExprie == null){
                cacheExprie = CacheBuilder.newBuilder().expireAfterWrite(time, timeUnit).build();
            }
            Object o = cacheExprie.get(key, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    //缓存没有直接返回null
                    return "-1";
                }
            });
            if ("-1" == o.toString()){
                set(key, value, time, timeUnit);
                return true;
            }
            return false;
        }catch (Exception e){
            return true;
        }
    }
}
